//
//  SYDTravelViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/14.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDTravelViewController.h"
#import "SYDTravelCell.h"
#import <QuartzCore/QuartzCore.h>
#import "SYDTravelDetailController.h"
#import "YMView.h"
#import "YMTravelTrackViewController.h"

static NSString *const TravelID = @"SYDTravelCell";

@interface SYDTravelViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataList;

@property (nonatomic, strong) YMNodataView * nodataView;
@property (nonatomic, strong) YMNodataView * noNetView;
@property (nonatomic, strong) YMNodataView * noServerView;

@end

@implementation SYDTravelViewController
#pragma mark - 导航栏
- (void)navigationBarHandle{
    
    WEAKSELF
    [weakSelf backButtonAction:^{
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationBar.title = @"行程订单";
    [self navigationBarHandle];
    [self initTravelUI];
}
-(void)initTravelUI{
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.separatorColor = SEPARATE_LINE_COLOR;
    [self.tableView registerNib:[UINib nibWithNibName:TravelID bundle:nil] forCellReuseIdentifier:TravelID];
    if(![SYDHasNetWork connectedToNetwork])
    {
        [self showNoNetView];
        [self.tableView reloadData];
        
    }else{
        [self getTravelDetailFromServer];
    }
}
-(void)getTravelDetailFromServer{
    WEAKSELF  //[YMSaveTool valueForKey:USER_ID]
    [[SYDNetwork shareTool]getMyTrailOrderWithUserId:[YMSaveTool valueForKey:USER_ID] success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            if (self.dataList.count > 0) {
                [self.dataList removeAllObjects];
            }
            if ([responseObject[@"statusCode"]integerValue] == 200) {
                if ([responseObject[@"obj"]isKindOfClass:[NSArray class]]) {
                    
                    NSArray *array = responseObject[@"obj"];
                    if (array.count > 0) {
                        weakSelf.dataList = [travelModel mj_objectArrayWithKeyValuesArray:responseObject[@"obj"]];
                    }else{
                        [weakSelf showNodata];
                    }
                }else{
                    [weakSelf showNodata];
                }
            }else{
                [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
            }
        } @catch (NSException *exception) {
            NSLog(@"%@",exception.description);
        } @finally {
        }
        [weakSelf.tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
//    NSDictionary *orderData = [NSString resourcePathWithFileName:@"walletDetail.json"];
//    self.dataList = [sydWalletDetailModel mj_objectArrayWithKeyValuesArray:orderData[@"obj"]];
//    [self.tableView reloadData];
}
#pragma mark---UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    travelModel *model = self.dataList[section];
    return model.myBriefReceivingOrders.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SYDTravelCell *cell = [tableView dequeueReusableCellWithIdentifier:TravelID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    travelModel *model = self.dataList[indexPath.section];
    NSArray *array = model.myBriefReceivingOrders;
    BriefOrderModel *briefOrderModel = array[indexPath.row];
    [cell travelCellWithModel:briefOrderModel];
    
    BOOL isDraw = NO;
    for (UIView * view in cell.contentView.subviews) {
        if ([view isKindOfClass:[YMView class]]) {
            isDraw = YES;
        }
    }
    
    if (indexPath.row != model.myBriefReceivingOrders.count - 1 && !isDraw) {
        YMView * line = [[YMView alloc] initWithFrame:CGRectMake(0, cell.contentView.height - 0.3, self.tableView.width, 0.3)];
        line.backgroundColor = [UIColor colorWithHexString:@"#e8e8e8"];
        [cell.contentView addSubview:line];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 107;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    travelModel *model = self.dataList[indexPath.section];
    NSArray *array = model.myBriefReceivingOrders;
    BriefOrderModel *briefOrderModel = array[indexPath.row];
    YMTravelTrackViewController *detailVc = [[YMTravelTrackViewController alloc]init];
    detailVc.orderNo = briefOrderModel.regularRouteOrderNo;
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(tintColor)]) {
        if (tableView == self.tableView) {
            // 圆角弧度半径
            CGFloat cornerRadius = 10.f;
            // 设置cell的背景色为透明，如果不设置这个的话，则原来的背景色不会被覆盖
            cell.backgroundColor = UIColor.clearColor;
            
            // 创建一个shapeLayer
            CAShapeLayer *layer = [[CAShapeLayer alloc] init];
            CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init]; //显示选中
            // 创建一个可变的图像Path句柄，该路径用于保存绘图信息
            CGMutablePathRef pathRef = CGPathCreateMutable();
            // 获取cell的size
            CGRect bounds = CGRectInset(cell.bounds, 0, 0);
            
            // CGRectGetMinY：返回对象顶点坐标
            // CGRectGetMaxY：返回对象底点坐标
            // CGRectGetMinX：返回对象左边缘坐标
            // CGRectGetMaxX：返回对象右边缘坐标
            
            // 这里要判断分组列表中的第一行，每组section的第一行，每组section的中间行
            BOOL addLine = NO;
            // CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
            if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
                // 初始起点为cell的左上角坐标
                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
                // 添加一条直线，终点坐标为右下角坐标点并放到路径中去
                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
                addLine = NO;
            } else {
                // 添加cell的rectangle信息到path中（不包括圆角）
                CGPathAddRect(pathRef, nil, bounds);
                addLine = NO;
            }
            
            // 把已经绘制好的可变图像路径赋值给图层，然后图层根据这图像path进行图像渲染render
            layer.path = pathRef;
            backgroundLayer.path = pathRef;
            // 注意：但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
            CFRelease(pathRef);
            // 按照shape layer的path填充颜色，类似于渲染render
            // layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
            layer.fillColor = [UIColor whiteColor].CGColor;
            // 添加分隔线图层
            if (addLine == YES) {
                CALayer *lineLayer = [[CALayer alloc] init];
                CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
                lineLayer.frame = CGRectMake(CGRectGetMinX(bounds), bounds.size.height-lineHeight, bounds.size.width, lineHeight);
                // 分隔线颜色取自于原来tableview的分隔线颜色
                lineLayer.backgroundColor = WHITE_COLOR.CGColor;
                [layer addSublayer:lineLayer];
            }
            
            // view大小与cell一致
            UIView *roundView = [[UIView alloc] initWithFrame:bounds];
            // 添加自定义圆角后的图层到roundView中
            [roundView.layer insertSublayer:layer atIndex:0];
            roundView.backgroundColor = UIColor.clearColor;
            //cell的背景view
            //cell.selectedBackgroundView = roundView;
            cell.backgroundView = roundView;
            
            //以上方法存在缺陷当点击cell时还是出现cell方形效果，因此还需要添加以下方法
            UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:bounds];
            backgroundLayer.fillColor = WHITE_COLOR.CGColor;
            [selectedBackgroundView.layer insertSublayer:backgroundLayer atIndex:0];
            selectedBackgroundView.backgroundColor = UIColor.clearColor;
            cell.selectedBackgroundView = selectedBackgroundView;
        }
    }
}
#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    static NSString * identy = @"head";
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    if (!hf) {
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH - 30,44)];
        view.backgroundColor = SEPARATE_LINE_COLOR;
        [hf addSubview:view];
        
        [hf drawBorderWithCornerRadius:5];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10,10)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        
        maskLayer.frame = view.bounds;
        
        maskLayer.path = maskPath.CGPath;
        
        view.layer.mask = maskLayer;
        travelModel *model = self.dataList[section];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, view.centerY - 7, 100, 14)];
        label.text = model.ID;
        label.textColor = SUB_TITLE_COLOR;
        label.textAlignment = NSTextAlignmentLeft;
        label.font = [UIFont systemFontOfSize:14];
        [view addSubview:label];
    }
    return hf;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 15;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
#pragma mark - Lazy
-(UITableView *)tableView{
    
    if (_tableView == nil) {
        if (iPhone8_X) {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(15, 88 + 10, SCREEN_WIDTH - 30, SCREEN_HEIGHT - 88 - 10) style:UITableViewStyleGrouped];
        } else {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(15, STATUS_AND_NAVIGATION_HEIGHT + 10, SCREEN_WIDTH - 30, SCREEN_HEIGHT - STATUS_AND_NAVIGATION_HEIGHT - 10) style:UITableViewStyleGrouped];
        }
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = CONTENT_BG_COLOR;
        _tableView.tipsStr = @"暂无行程记录！";
        _tableView.reloadBtn = YES;
        WEAKSELF
        _tableView.reloadClickBlock = ^{
            NSLog(@"reload data");
            NSInteger count = weakSelf.navigationController.viewControllers.count;
            [weakSelf.navigationController popToViewController:weakSelf.navigationController.viewControllers[count - 3] animated:YES];
        };
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(NSMutableArray *)dataList{
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

//无网络,连接失败
- (YMNodataView *)noNetView{
    if (!_noNetView) {
        if (iPhone8_X) {
            _noNetView = [[YMNodataView alloc]initWithFrame:CGRectMake(0, 88, SCREEN_WIDTH, SCREEN_HEIGHT - 88) image:[UIImage imageNamed:@"icon_withdrawal"] imageWidth:132 title:@"网络连接失败,请查看网络是否连接正常！"];
        } else {
            _noNetView = [[YMNodataView alloc]initWithFrame:CGRectMake(0, STATUS_AND_NAVIGATION_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_AND_NAVIGATION_HEIGHT) image:[UIImage imageNamed:@"icon_withdrawal"] imageWidth:132 title:@"网络连接失败,请查看网络是否连接正常！"];
        }
    }
    return _noNetView;
}

- (void)showNoNetView{
    
    self.tableView.tableFooterView = self.noNetView;
}

- (void)hideNoNetView{
    self.tableView.tableFooterView = nil;
}

//无数据
- (YMNodataView *)nodataView{
    if (!_nodataView) {
        if (iPhone8_X) {
            _nodataView = [[YMNodataView alloc]initBigImageWithFrame:CGRectMake(0, 88, SCREEN_WIDTH, SCREEN_HEIGHT - 88) image:[UIImage imageNamed:@"icon_withdrawal"] title:@"暂无行程记录！"];
        } else {
            _nodataView = [[YMNodataView alloc]initBigImageWithFrame:CGRectMake(0, STATUS_AND_NAVIGATION_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_AND_NAVIGATION_HEIGHT) image:[UIImage imageNamed:@"icon_withdrawal"] title:@"暂无行程记录！"];
        }
        
    }
    return _nodataView;
}

- (void)showNodata{
    self.tableView.tableFooterView = self.nodataView;
}

- (void)hideNodata{
    self.tableView.tableFooterView = nil;
    
}

// 服务器错误
- (YMNodataView *)noServerView{
    if (!_noServerView) {
        if (iPhone8_X) {
            _noServerView = [[YMNodataView alloc]initBigImageWithFrame:CGRectMake(0, 88, SCREEN_WIDTH, SCREEN_HEIGHT - 88) image:[UIImage imageNamed:@"icon_withdrawal"] title:@"服务器连接失败，请稍后再试！"];
        } else {
            _noServerView = [[YMNodataView alloc]initBigImageWithFrame:CGRectMake(0, STATUS_AND_NAVIGATION_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_AND_NAVIGATION_HEIGHT) image:[UIImage imageNamed:@"icon_withdrawal"] title:@"服务器连接失败，请稍后再试！"];
        }
        
    }
    return _noServerView;
}

- (void)showNoServerView{
    self.tableView.tableFooterView = self.noServerView;
}

- (void)hideNoServerView{
    self.tableView.tableFooterView = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end








































